package com.v9.main.controller.common;

import com.v9.common.core.service.TreeDataProvider;
import com.v9.common.dto.ProviderTypeDto;
import com.v9.common.dto.TreeNodeDto;
import com.v9.common.exception.ApplicationException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lunshi
 */
@RestController
@Tag(name = "树数据提供器")
@RequestMapping(value = "/sys/tree/", method = RequestMethod.POST)
public class TreeDataProviderController implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @RequestMapping("data/{treeType}")
    @Operation(summary = "树控件值")
    public List<TreeNodeDto> build(@PathVariable String treeType) {
        String[] beanNamesForType = this.applicationContext.getBeanNamesForType(TreeDataProvider.class);
        for (String type : beanNamesForType) {
            TreeDataProvider bean = (TreeDataProvider) applicationContext.getBean(type);
            if (bean.treeTypeCode().equals(treeType)) {
                return bean.buildTreeData();
            }
        }
        throw new ApplicationException("非法操作");
    }

    @RequestMapping("types")
    @Operation(summary = "树控件类型")
    public List<ProviderTypeDto> types() {
        String[] beanNamesForType = this.applicationContext.getBeanNamesForType(TreeDataProvider.class);
        List<ProviderTypeDto> results = new ArrayList<>();
        for (String type : beanNamesForType) {
            TreeDataProvider bean = (TreeDataProvider) applicationContext.getBean(type);
            ProviderTypeDto e = new ProviderTypeDto();
            e.setName(bean.buildTreeTypeName());
            e.setCode(bean.treeTypeCode());
            results.add(e);
        }
        return results;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


}
